# -*- coding:utf-8 -*-
import web, models, service
from baseHandler import BaseHandler
from utils.decorator import render

class CompanyCase(BaseHandler):
    @render('caseDetail.html')
    def GET(self, branchCompanyId, caseId):
        user = self.getCurrentUser()
        branchCompanyId = long(branchCompanyId)
        caseId = long(caseId)
        service.Company.getBranchCompany(branchCompanyId)
        hasOverviewRight = service.User.hasOverviewRight(user)

        if not hasOverviewRight and branchCompanyId != user.company_id:
            raise web.seeother('/company/%d/case/%d' % (user.company_id, caseId))

        branchCompanys = models.Company.getBatchByType(models.Company.TYPE_BRANCH) if hasOverviewRight else [models.Company.getById(user.company_id)]

        case = service.Case.getCase(caseId, branchCompanyId)

        actions = service.Action.getFormatActions(caseId)
        case.value = service.formatMoney(case.value)
        return {'title' : u'未结案件明细', 'branch_companys' : branchCompanys, 'active_company_id' : branchCompanyId, 'active_type' : 'unfinished', 'case' : case, 'actions' : actions, 'can_overview' : hasOverviewRight}

    @render(None, 'json')
    def POST(self, branchCompanyId, caseId):
        user = self.getCurrentUser()

        service.User.canOperate(user, branchCompanyId)

        branchCompanyId = long(branchCompanyId)
        caseId = long(caseId)
        service.Company.getBranchCompany(branchCompanyId)
        service.Case.getCase(caseId, branchCompanyId)
        action = web.input().get('action')
        print web.input()
        if 'push' == action:
            service.Operation.pushCase(caseId, user)
        elif 'receive' == action:
            service.Operation.receiveCase(caseId, user)
        elif 'undo' == action:
            service.Operation.undoCase(caseId, user)
        elif 'return' == action:
            service.Operation.returnCase(caseId, user)
        elif 'modify' == action:
            value = long(float(web.input().get('value') or 0) * 100)
            address = web.input().get('address')
            reason = web.input().get('reason')
            insurance_time = web.input().get('insurance_time')
            service.Operation.modifyCase(caseId, user, address, reason, insurance_time, value)
        else:
            raise web.notfound()
        raise web.seeother('/company/%d/case/%d' % (branchCompanyId, caseId))



